package com.example.questionbase.util;

import com.hankcs.hanlp.HanLP;
import com.hankcs.hanlp.dictionary.CustomDictionary;
import org.springframework.core.io.ClassPathResource;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author: fan
 * @Description: TODO
 * @Date: 2024/03/02 13:12
 */
public final class WordUtil {

    private static boolean isCustomDictLoaded = false;

    private WordUtil() {
    }

    /**
     * 加载自定义词典
     *
     * @throws IOException
     */
    private static void loadCustomDictionary() throws IOException {
        if (!isCustomDictLoaded) {
            ClassPathResource resource = new ClassPathResource("terminology.txt");
            InputStream in = resource.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
            String line;
            while ((line = reader.readLine()) != null) {
                CustomDictionary.add(line);// 添加词语到自定义词典
            }
            reader.close();
            isCustomDictLoaded = true;
        }
    }

    /**
     * 提取文本关键字
     *
     * @param text
     * @return
     */
    public static List<String> extractKeywords(String text) {
        if (!isCustomDictLoaded) {
            try {
                loadCustomDictionary();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        List<String> keywordList = new ArrayList<>();
        List<String> wordList = HanLP.segment(text).stream().map(term -> term.word).toList(); // 分词
        for (String word : wordList) {
            if (HanLP.extractKeyword(word, 1).contains(word)) { // 判断是否是关键词
                keywordList.add(word);
            }
        }
        return keywordList;
    }

    /**
     * 字符列表转字符串
     *
     * @param list
     * @return
     */
    public static String listToString(List<String> list) {
        if (!isCustomDictLoaded) {
            try {
                loadCustomDictionary();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            if (i == list.size() - 1) {
                builder.append(list.get(i));
            } else {
                builder.append(list.get(i)).append(";");
            }
        }
        return builder.toString();
    }

    public static void syntaxCheck(String text) {
        String syntaxTree = String.valueOf(HanLP.parseDependency(text));
        // 打印语法分析结果
        System.out.println(syntaxTree);
    }
}
